package com.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.mapper.AdminMapper;
import com.common.model.Admin;
import com.common.query.AdminQueryParam;
import com.common.service.AdminService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    private AdminMapper adminMapper;

    public AdminServiceImpl(AdminMapper adminMapper) {
        this.adminMapper = adminMapper;
    }

    @Override
    public List<Admin> findAll() {
        return adminMapper.selectAll();
    }

    @Override
    public Admin findByAdminId(long id) {
        return adminMapper.selectById(id);
    }

    @Override
    public Admin findByUsername(String username) {

        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username", username);

        return adminMapper.selectOne(qw);
    }

    @Override
    public int save(Admin admin) {

        if (admin.getRegisterTime() == null) {
            admin.setRegisterTime(String.valueOf(System.currentTimeMillis()));
        }

        return adminMapper.insert(admin);
    }

    @Override
    public void edit(Admin admin) {
        adminMapper.updateById(admin);
    }

    @Override
    public void delete(long id) {
        adminMapper.deleteById(id);
    }

    @Override
    public IPage<Admin> findAll(Integer page, Integer pageSize) {

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderBy(true, false, "article_id");

        return adminMapper.selectPage(new Page<>(page, pageSize), queryWrapper);
    }

    @Override
    public IPage<Admin> findAll(Integer page, Integer pageSize, AdminQueryParam adminQueryParam) {

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderBy(true, false, "article_id");

        if (adminQueryParam.getUsername() != null) {
            queryWrapper.like("usernmae", adminQueryParam.getUsername());
        }

        return adminMapper.selectPage(new Page<>(page, pageSize), queryWrapper);
    }
}
